/*
 * @Author: LiZhiWei
 * @Date: 2025-07-15 10:18:11
 * @LastEditors: wjc
 * @LastEditTime: 2025-10-29 17:53:36
 * @Description: 统一的详情显示功能Hook，支持弹窗显示和页面显示
 */
import { api, Http } from '#/api'

export function useShower(
  options: {
    entity?: string
    formSize?: 'large' | 'mini' | 'normal' | string
    message?: string
    mode?: BaseFormMode
    url?: RequestUrl
  } = {
    mode: 'dialog',
    formSize: 'normal',
    entity: '',
    message: '',
  }
) {
  const { entity = '', url, formSize = 'normal' } = options
  const loading = ref(false)
  const model = ref<any>({})
  const columns = ref([])
  const route = useRoute()
  const modelId = route.params.id

  // 弹窗显示相关
  const showDialog = ref({
    id: modelId as number | string,
    visible: false,
    entity,
    size: formSize,
  })

  const showShower = (id: number | string) => {
    showDialog.value.id = id
    showDialog.value.visible = true
  }

  // 核心显示函数
  const show = (url: string, params: any) => {
    loading.value = true

    return Http.Get<any>(url, { params })
      .then((res) => {
        model.value = res.data
        columns.value = Object.prototype.hasOwnProperty.call(res, 'columns') ? res.columns : []
        return res
      })
      .finally(() => {
        loading.value = false
      })
  }

  // 显示后回调处理
  const afterShowed = (res: any, onShowed?: (res: any) => void) => {
    onShowed && onShowed(res)
  }
  // 重构后的 fetchData 函数，保持向后兼容
  const fetchData = (fetchOptions?: { id?: number | string; onFetched?: (res: any) => void }) => {
    const { id, onFetched } = fetchOptions || {}
    show(api[entity].show(id || modelId), url?.params).then((res) => {
      afterShowed(res, onFetched)
    })
  }

  // 自定义URL数据获取函数
  const fetchDataWith = (requestUrl: RequestUrl, onFetched?: (res: any) => void) => {
    show(requestUrl.show as string, requestUrl.params).then((res) => {
      afterShowed(res, onFetched)
    })
  }

  const getReturnRoute = (routeName?: string) => {
    return routeName || `${entity}Index`
  }

  return {
    loading,
    modelId,
    columns,
    model,
    showDialog,
    showShower,
    getReturnRoute,
    fetchData,
    fetchDataWith,
  }
}
